<?php

header("Cache-Control: no-cache, must-revalidate"); // HTTP/1.1
header("Expires: Thu, 1 Jan 1970 01:00:00 GMT"); // Date in the past
header('Content-type: text/JavaScript');
error_reporting(E_ERROR | E_PARSE | E_CORE_ERROR);
ini_set('log_errors', '1');
ini_set('error_log', 'php_error.log');
ini_set('display_errors', '1');

include_once("file.common.php");
authenticate($validCredentials);

// Input
$file = req('file', '');
$path = req('path', '');
$key = req('key');
$rmDir = req('rmDir', FALSE);
$callbackName = req('callback');
$devPassword = req('devPassword');

$result = TRUE;
$ot = $aot = '';
$isFolder = FALSE;
$exists = FALSE;
$msg = 0;

$fullPath = webPath($path, $file);

$pi = pathinfo($fullPath);

// Prevent deleting files outside this space with a few exceptions
if (strpos($fullPath, '../../') !== FALSE)
{
	if (!$devPassword || $devPassword != $devPasscode)
		exit(0);
}


/** 
 * Recursively delete a directory 
 * 
 * @param string $dir Directory name 
 * @param boolean $deleteRootToo Delete specified top-level directory as well 
 */ 
function unlinkRecursive($dir, $deleteRootToo) 
{ 
    if(!$dh = @opendir($dir)) 
    { 
        return false;
    } 
    while (false !== ($obj = readdir($dh))) 
    { 
        if($obj == '.' || $obj == '..') 
        { 
            continue; 
        } 

        if (!@unlink($dir . '/' . $obj)) 
        { 
            unlinkRecursive($dir.'/'.$obj, true); 
        } 
    } 

    closedir($dh); 
    
    if ($deleteRootToo) 
    { 
        return @rmdir($dir); 
    } 
    
    return true; 
} 

if (file_exists($fullPath)) {
	$exists = TRUE;
	if (is_dir($fullPath)) {
		$result = unlinkRecursive($fullPath, $rmDir);
		$isFolder = TRUE;
	} else {
		unlink($fullPath);
		clearstatcache();
		$result = !file_exists($fullPath);
	}
}
else {
	$result = TRUE;
	$msg = 'file does not exist';
}

$ot .= "$callbackName({\n";
$ot .= '"result":' . json_encode($result) . ",\n";
$ot .= '"file":' . json_encode($file) . ",\n";
$ot .= '"path":' . json_encode($path) . ",\n";
$ot .= '"fullPath":' . json_encode($fullPath) . ",\n";
$ot .= '"rmDir":' . json_encode($rmDir) . ",\n";
$ot .= '"cwd":' . json_encode(getcwd()) . ",\n";
$ot .= '"root":' . json_encode($_ENV['DOCUMENT_ROOT']) . ",\n";
$ot .= '"msg":' . json_encode($msg) . ",\n";
$ot .= '"key":' . json_encode($key) . ",\n";
$ot .= '"host":' . json_encode($_ENV['SERVER_NAME']) . ",\n";
$ot .= '"exists":' . json_encode($exists) . ",\n";
if ($devserver) {
	$ot .= '"cwd":' . json_encode(getcwd()) . ",\n";
	$ot .= '"root":' . json_encode($_SERVER['DOCUMENT_ROOT']) . ",\n";
}
$ot .= '"end":true' . "\n";
$ot .= "})";
echo $ot;
?>
